//
//  MSSearchPriceResult.m
//  MS
//
//  Created by Yuan on 13-4-6.
//  Copyright (c) 2013年 He Yuan. All rights reserved.
//

#import "MSSearchResultCell.h"
#import "MSSearchPriceResult.h"
#import "UIButton+WebCache.h"

@interface MSSearchPriceResult ()<UITableViewDataSource,UITableViewDelegate>
{
    NSMutableDictionary *searchConditions;
    
    NSInteger currentPage;
    BOOL isNextPage;
    
    BOOL isSearching;
    
    UITableView *resultTableView;
    
    NSMutableArray *dataArray;
}
@property(nonatomic,retain) UITableView *resultTableView;

@property(nonatomic,retain) NSMutableArray *dataArray;

@end

@implementation MSSearchPriceResult
@synthesize resultTableView;
@synthesize dataArray;
@synthesize loadFooterView;


- (void)viewDidUnload {
    resultTableView = nil;
	loadFooterView=nil;
}

- (void)dealloc {
    resultTableView = nil;
	loadFooterView = nil;
}


- (id)initWithInfo:(NSDictionary *)info
{
    self = [super init];
    if (self)
    {
        currentPage = 1;
        
        isNextPage = YES;
        
        dataArray = [[NSMutableArray alloc]init];
        
        searchConditions = [[NSMutableDictionary alloc]initWithDictionary:info];
    }
    return self;
}

-(void)loadView
{
    [super loadView];
    
    resultTableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    resultTableView.backgroundColor = [UIColor clearColor];
    resultTableView.backgroundView = nil;
    resultTableView.delegate = self;
    resultTableView.dataSource = self;
    resultTableView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleBottomMargin;
    [self.view addSubview:self.resultTableView];    

    loadFooterView = [[LoadMoreView alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
    [resultTableView addSubview:loadFooterView];

}


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setTitle:@"发型师" showBackButton:YES];

    [self search];
}


-(void)configureViews:(BOOL)animation
{
    [super configureViews:animation];
}

-(void)search
{
    if (isSearching) {
        return;
    }
    
    isSearching = YES;
    
    [searchConditions setObject:[NSNumber numberWithInt:currentPage] forKey:@"page"];
    [searchConditions setObject:[[MSSetting sharedSetting]getAccountID] forKey:@"uid"];
    [searchConditions setObject:[[MSSetting sharedSetting]getGid] forKey:@"gid"];
    [WebService  getRequestAction:APISearch
                            param:searchConditions
                          success:^(NSDictionary *info,NSError *error)
     {
         isNextPage = NO;
         
         if (error == nil)
         {
             HYLog(@"%@",info);
             if (info && [info isKindOfClass:[NSDictionary class]])
             {
                 currentPage ++;
                 NSArray *result = [info objectForKey:@"result"];
                 if (result && [result isKindOfClass:[NSArray class]] && [result count]>0)
                 {
                     isNextPage = YES;
                 }
                 [dataArray addObjectsFromArray:[info objectForKey:@"result"]];
                 [self reloadData];
             }
         }
         isSearching = NO;
         [MSTool showError:error];
     } failure:^(id info ,NSError *error){
         [MSTool showError:error];
         isSearching = NO;
     } progress:(currentPage == 1)?self.view:nil];
}

-(void)reloadData
{
    [self.resultTableView reloadData];
    UIViewSetFrameY(loadFooterView, resultTableView.contentSize.height);
    [resultTableView setContentSize:CGSizeMake(0, resultTableView.contentSize.height+40)];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [dataArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tb cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    MSSearchResultCell *cell = [tb dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[MSSearchResultCell  alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    }
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.selectionStyle = UITableViewCellSelectionStyleBlue;
    NSDictionary *item = [dataArray objectAtIndex:indexPath.row];
    cell.aliasLbl.text = [item objectForKey:@"user_name"];
    cell.storeNameLbl.text = [item objectForKey:@"salon"];
    cell.addressbl.text = [item objectForKey:@"address"];
        
    if ([[item objectForKey:@"follow"] boolValue])
    {
        [cell.addButton setImage:[UIImage imageNamed:@"un_followbtn.png"] forState:UIControlStateNormal];
    }
    else
    {
        [cell.addButton setImage:[UIImage imageNamed:@"followbtn.png"] forState:UIControlStateNormal];
    }
    
    if ([item objectForKey:@"avatar"])
    {
        [cell.iconButton setImageWithURL:[NSURL URLWithString:[item objectForKey:@"avatar"]] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"Icon.png"]];
    }
    else
    {
        [cell.iconButton setImage:[UIImage imageNamed:@"Icon.png"] forState:UIControlStateNormal];
    }
    [cell.addButton addTarget:self action:@selector(followUser:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 82.0f;
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    loadFooterView.hidden = !isNextPage;   
    return [[UIView alloc]initWithFrame:CGRectZero];
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tb didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tb deselectRowAtIndexPath:indexPath animated:YES];
}

-(void)followUser:(UIButton *)btn
{
    MSSearchResultCell *cell = (MSSearchResultCell *)btn.superview.superview;
    NSIndexPath *indexPath = [self.resultTableView indexPathForCell:cell];
    NSDictionary *item = [dataArray objectAtIndex:indexPath.row];
    HYLog(@"%@",item);
    NSDictionary *p = [NSDictionary dictionaryWithObjectsAndKeys:
                   [[MSSetting sharedSetting]getAccountID],@"uid",
                   [item objectForKey:@"uid"],@"follow_uid",nil];
    if ([[item objectForKey:@"follow"] boolValue])
    {
        [WebService  getRequestAction:APIUnFollow
                                param:p
                              success:^(NSDictionary *info,NSError *error)
         {
             if (error == nil)
             {
                 HYLog(@"%@",info);
                 [MSTool refreshHUDText:HYLocalizedString(@"处理成功!")];
                 [self handleSuccessed:indexPath.row follow:NO];
             }
             [MSTool showError:error];
         } failure:^(id info ,NSError *error){
             [MSTool showError:error];
         } progress:self.navigationController.view];
    }
    else
    {
        [WebService  getRequestAction:APIFollow
                                param:p
                              success:^(NSDictionary *info,NSError *error)
         {
             if (error == nil)
             {
                 HYLog(@"%@",info);
                 [MSTool refreshHUDText:HYLocalizedString(@"处理成功!")];
                 [self handleSuccessed:indexPath.row follow:YES];
             }
             [MSTool showError:error];
         } failure:^(id info ,NSError *error){
             [MSTool showError:error];
         } progress:self.navigationController.view];
    }
}

-(void)handleSuccessed:(NSInteger)idx follow:(BOOL)follow
{
    NSDictionary *item = [dataArray objectAtIndex:idx];
    NSMutableDictionary *changeDict = [[NSMutableDictionary alloc]initWithDictionary:item];
    [changeDict setObject:[NSNumber numberWithBool:follow] forKey:@"follow"];
    [dataArray replaceObjectAtIndex:idx withObject:changeDict];
    changeDict = nil;
    [self.resultTableView reloadData];
}


#pragma scrollview delegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //    HYLog(@"%@",NSStringFromCGPoint(scrollView.contentOffset));
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.y > self.resultTableView.contentSize.height - 44  -  self.resultTableView.frame.size.height && isNextPage)
    {
        [self.loadFooterView startActivity];
        [self didStartRequest];
    }
    
    loadFooterView.hidden = !isNextPage;
}

#pragma #
#pragma load more methord
-(void)didStartRequest
{
    [self search];
    //reload subclass
    
}

-(void)didFinsihedRequest
{
    //reload subclass
    
    [self.loadFooterView stopActivity];
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
